package cn.dt70.controller;


import cn.dt70.pojo.*;
import cn.dt70.service.*;
import cn.dt70.utils.Constants;
import cn.dt70.utils.Xiangqing;
import cn.dt70.utils.suiji;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/Store/")
public class StoreConroller_ZHN {

    @Resource
    private AqbCommodityService aqbCommodityService;

    @Resource
    private AqbOrderService aqbOrderService;

    @Resource
    private AqbAddressService aqbAddressService;

    @Resource
    private AqbPacketsandinterestService aqbPacketsandinterestService;

    @Resource
    private AqbGrowthService aqbGrowthService;

    @Resource
    private AqbUserService aqbUserService;

    @Resource
    private AqbEntityorderService aqbEntityorderService;

    @Resource
    private AqbEntitycommodityService aqbEntitycommodityService;

    @Resource
    private AqbPacketService aqbPacketService;

    @RequestMapping("doStore")
    public String doStore(Model model,HttpSession session){
        if( session.getAttribute(Constants.USER_SESSION) == null){
            return "/index";
        }
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);

        session.setAttribute("money",aqbUser.getMoney());
        return "Store_ZHN/membermall";
    }


    @RequestMapping(value = "storeShitiList",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String storeShitiList(HttpSession session){

        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION); //获得帮主的等级
        String userCode = aqbUser.getUserCode(); //获得帮主的等级
        System.out.println("userCode:"+userCode);
        AqbGrowth aqbGrowth = aqbGrowthService.getGrowthByUserCode(userCode); //获得帮主的等级
        String grade1 = aqbGrowth.getGrade();
       session.setAttribute("money",aqbUser.getMoney());



        String grade =aqbGrowth.getGrade();//获得帮主的等级
        double zhekou =1;    //计算折扣
        if(grade.equals("v1")){  //计算折扣
            zhekou =1 ;
        }else if(grade.equals("v2")){  //计算折扣
            zhekou = 0.98;
        }else if(grade.equals("v3")){  //计算折扣
            zhekou =0.95;
        }else if(grade.equals("v4")){  //计算折扣
            zhekou =0.9;
        }else if(grade.equals("v5")){  //计算折扣
            zhekou =0.85;
        }else if(grade.equals("vip")){  //计算折扣
            zhekou =8;
        }

        StringBuffer sb = new StringBuffer("{");
        List<AqbCommodity> aqbCommodityList =new ArrayList<AqbCommodity>();
        List<AqbCommodity> aqbCommodityList2 =new ArrayList<AqbCommodity>();
        aqbCommodityList = aqbCommodityService.getShiti(); //获得全部实体商品信息
        aqbCommodityList2 =aqbCommodityService.getHB();   //获得全部的虚拟商品信息
        for(int i=0;i<aqbCommodityList2.size();i++){     //遍历信息并往里添加库存信息
           double type = (double)aqbCommodityList2.get(i).getHBtype();
                int HBkucun = aqbPacketsandinterestService.qrytypeValueforstock(type);
                aqbCommodityList2.get(i).setHBkucun(HBkucun);
        }

        //额外计算折扣金钱
        double numprice ;
        for(int i=0;i<aqbCommodityList.size();i++){
            numprice = aqbCommodityList.get(i).getPrice();
            aqbCommodityList.get(i).setNewprice(numprice*zhekou);
        }

        for(int i=0;i<aqbCommodityList2.size();i++){
            numprice = aqbCommodityList2.get(i).getPrice();
            aqbCommodityList2.get(i).setNewprice(numprice*zhekou);
        }

        sb.append("\"Ld\":"+ JSON.toJSON(aqbCommodityList.get(0)));
        sb.append(",");
        sb.append("\"Ld21\":"+ JSON.toJSON(aqbCommodityList2.get(0)));
        sb.append(",");
        sb.append("\"Ld22\":"+ JSON.toJSON(aqbCommodityList2.get(1)));
        sb.append(",");
        sb.append("\"LdList\":"+ JSON.toJSON(aqbCommodityList));
        sb.append(",");
        sb.append("\"LdList2\":"+ JSON.toJSON(aqbCommodityList2));
        sb.append("}");
        return sb.toString();
    }

    @RequestMapping("doExchangelog")
    public String doExchangelog(Model model){
        return "Store_ZHN/MemberMall-exchangelog";
    }

    @RequestMapping(value = "exchangelogList",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String exchangelogList(@Param("page") int page,HttpSession session){
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        StringBuffer sb = new StringBuffer("{");
        List<AqbOrder> aqbOrderList =new ArrayList<AqbOrder>();
        aqbOrderList=  aqbOrderService.getAllOrder(aqbUser.getUserId(),(page-1)*5,5);   //BY  UserID
        int count =aqbOrderService.getOrderCountbyId(1);    //BY  UserID
        count = count/5+1;
        if(aqbOrderList == null || aqbOrderList.size()<1){
            sb.append("\"flag\":\"F\"");
            sb.append("}");
            return sb.toString();
        }else {
            sb.append("\"flag\":\"T\",");
            sb.append("\"LdList\":"+ JSON.toJSON(aqbOrderList)+",");
            sb.append("\"Count\":"+count);
            sb.append("}");
            return sb.toString();
        }

    }

    @RequestMapping("doExchangelog2")
    public String doExchangelog2(Model model){
        return "Store_ZHN/MemberMall-exchangelog2";
    }

    @RequestMapping("doExchangelog3")
    public String doExchangelog3(Model model){
        return "Store_ZHN/MemberMall-exchangelog3";
    }


    @RequestMapping(value = "exchangelogList2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String exchangelogList2(@Param("page") int page, HttpSession session){
        StringBuffer sb = new StringBuffer("{");
        List<AqbOrder> aqbOrderList =new ArrayList<AqbOrder>();
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        aqbOrderList=  aqbOrderService.getAllOrder2(aqbUser.getUserId(),(page-1)*5,5);    //BY  UserID
        int count =aqbOrderService.getOrderCountbyId(aqbUser.getUserId());    //BY  UserID
        count = count/5+1;
        if(aqbOrderList == null || aqbOrderList.size()<1){
            sb.append("\"flag\":\"F\"");
            sb.append("}");
            return sb.toString();
        }else {
            sb.append("\"flag\":\"T\",");
            sb.append("\"LdList\":"+ JSON.toJSON(aqbOrderList)+",");
            sb.append("\"Count\":"+count);
            sb.append("}");
            return sb.toString();
        }

    }

    @RequestMapping(value = "exchangelogList3",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String exchangelogList3(@Param("page") int page,HttpSession session){
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        StringBuffer sb = new StringBuffer("{");
        List<AqbOrder> aqbOrderList =new ArrayList<AqbOrder>();
        aqbOrderList=  aqbOrderService.getAllOrder3(aqbUser.getUserId(),(page-1)*5,5);   //BY  UserID
        int count =aqbOrderService.getOrderCountbyId(1);    //BY  UserID
        count = count/5+1;
        if(aqbOrderList == null || aqbOrderList.size()<1){
            sb.append("\"flag\":\"F\"");
            sb.append("}");
            return sb.toString();
        }else {
            sb.append("\"flag\":\"T\",");
            sb.append("\"LdList\":"+ JSON.toJSON(aqbOrderList)+",");
            sb.append("\"Count\":"+count);
            sb.append("}");
            return sb.toString();
        }

    }

//    @RequestMapping(value = "exchangelogList3",produces = "application/json;charset=utf-8")
//    @ResponseBody
//    public String exchangelogList3(@Param("page") int page, HttpSession session){
//        StringBuffer sb = new StringBuffer("{");
//        List<AqbOrder> aqbOrderList =new ArrayList<AqbOrder>();
//        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
//        aqbOrderList=  aqbOrderService.getAllOrder3(aqbUser.getUserId(),(page-1)*5,5);    //BY  UserID
//        return sb.toString();
//    }

    @RequestMapping("doDizhi")
    public String doDizhi(Model model){
        return "Store_ZHN/MemberMall-address";
    }


    @RequestMapping(value = "DizhiList",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String DizhiList(Model model,@Param("userId")int userId, HttpSession session){
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        StringBuffer sb = new StringBuffer("{");
        List<AqbAddress> aqbAddressList = new ArrayList<AqbAddress>();
         aqbAddressList = aqbAddressService.getAddressByUserid(aqbUser.getUserId());   //BY  UserID
         AqbAddress aqbAddress = aqbAddressList.get(0);
            sb.append("\"LdList\":"+ JSON.toJSON(aqbAddressList));
            sb.append(",\"First\":"+JSON.toJSON(aqbAddress));
            sb.append("}");
            return sb.toString();
    }

    @RequestMapping(value = "DizhiByAddId",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String DizhiByAddId (Model model,@Param("addId")int addId){
        StringBuffer sb = new StringBuffer("{");
        AqbAddress aqbAddress = new AqbAddress();
        aqbAddress = aqbAddressService.getAddressByAddid(addId);
        sb.append("\"aqbAddress\":"+JSON.toJSON(aqbAddress));
        sb.append("}");
        return sb.toString();
    }

    @RequestMapping(value = "addAddress",produces = "application/json;charset=utf-8")
    @ResponseBody
    public  String addAddress(Model model,
                              @Param("addressName")String addressName,
                              @Param("provicace")String provicace,
                              @Param("city")String city,
                              @Param("district")String district,
                              @Param("address")String address,
                              @Param("phone")String phone, HttpSession session){
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        StringBuffer sb = new StringBuffer("{");
        boolean flag = aqbAddressService.addAddress(aqbUser.getUserId(),addressName,provicace,city,district,address,phone);  //byUserID
        if(flag == true){
            sb.append("\"flag\":\"T\"");

        }else {
            sb.append("\"flag\":\"F\"");
        }
        sb.append("}");
        return sb.toString();
    }


    @RequestMapping("xiangqing")
    public String xiangqing(String id,Model model,HttpSession session){
        AqbCommodity aqbCommodity =new AqbCommodity();
        int commodityId = Integer.parseInt(id);
        aqbCommodity = aqbCommodityService.getAqbCommodityBYAqbCommodity(commodityId);

        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        String userCode = aqbUser.getUserCode();
        AqbGrowth aqbGrowth = aqbGrowthService.getGrowthByUserCode(userCode); //获得帮主的等级
        String grade =aqbGrowth.getGrade();//获得帮主的等级
        double zhekou =1;    //计算折扣
        if(grade.equals("v1")){  //计算折扣
            zhekou =1 ;
        }else if(grade.equals("v2")){  //计算折扣
            zhekou = 0.98;
        }else if(grade.equals("v3")){  //计算折扣
            zhekou =0.95;
        }else if(grade.equals("v4")){  //计算折扣
            zhekou =0.9;
        }else if(grade.equals("v5")){  //计算折扣
            zhekou =0.85;
        }else if(grade.equals("vip")){  //计算折扣
            zhekou =8;
        }




        int flag = aqbCommodity.getCommoditytype();
        if(flag == 1){
            int conid =aqbCommodity.getCommodityId();
            int count = aqbCommodityService.getShitiCount(conid);
            aqbCommodity.setCommodityCount(count);
            aqbCommodity.setNewprice(aqbCommodity.getPrice()*zhekou);
        }else if(flag == 0){
            int conid =aqbCommodity.getCommodityId();
            double type = (double)aqbCommodityService.getHBtype(conid);
            int HBkucun = aqbPacketsandinterestService.qrytypeValueforstock(type);
            aqbCommodity.setNewprice(aqbCommodity.getPrice()*zhekou);
            aqbCommodity.setHBkucun(HBkucun);

        }
        session.setAttribute("aqbCommodity",aqbCommodity);

        return "Store_ZHN/MemberMall-xiangqing";
    }

    @RequestMapping(value = "Gouwuche",produces = "application/json;charset=utf-8")
    public String Gouwuche(int commodityId,double price, int num, int commoditytype,int shengyu,HttpSession session){
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        AqbCommodity aqbCommodity=aqbCommodityService.getAqbCommodityBYAqbCommodity(commodityId);
        String userCode = aqbUser.getUserCode(); //获得帮主的等级
        AqbGrowth aqbGrowth = aqbGrowthService.getGrowthByUserCode(userCode); //获得帮主的等级
        String grade =aqbGrowth.getGrade();//获得帮主的等级
        double zhekou =1;    //计算折扣
        if(grade.equals("v1")){  //计算折扣
            zhekou =1 ;
        }else if(grade.equals("v2")){  //计算折扣
            zhekou = 0.98;
        }else if(grade.equals("v3")){  //计算折扣
            zhekou =0.95;
        }else if(grade.equals("v4")){  //计算折扣
            zhekou =0.9;
        }else if(grade.equals("v5")){  //计算折扣
            zhekou =0.85;
        }else if(grade.equals("vip")){  //计算折扣
            zhekou =8;
        }
        Xiangqing xiangqing =new Xiangqing();
        List<AqbCommodity> aqbCommodityList =new ArrayList<AqbCommodity>();
        List<AqbUser> aqbUserList =new ArrayList<AqbUser>();
       if(session.getAttribute("xiangqing") != null){
           xiangqing = (Xiangqing) session.getAttribute("xiangqing");
           aqbCommodity.setNewprice(aqbCommodity.getPrice()*zhekou);
           aqbCommodity.setNum(num);
           aqbCommodity.setHBkucun(shengyu);
           xiangqing.addList(aqbCommodity);
           xiangqing.setPrices( xiangqing.getAllprices());
           session.setAttribute("xiangqing",xiangqing);
           System.out.println("有没有执行这个方法？？？？？？？？"+xiangqing.getAqbCommodity().size());
       }else {
           aqbCommodity.setNewprice(aqbCommodity.getPrice()*zhekou);
           aqbCommodity.setNum(num);
           aqbCommodity.setHBkucun(shengyu);
           aqbCommodityList = new ArrayList<AqbCommodity>();
           aqbUserList =new ArrayList<AqbUser>();
           aqbCommodityList.add(aqbCommodity);
           xiangqing.setAqbCommodity(aqbCommodityList);
           aqbUserList.add(aqbUser);
           xiangqing.setAqbUser(aqbUserList);
           xiangqing.setPrices( xiangqing.getAllprices());
           session.setAttribute("xiangqing",xiangqing);
       }

        return "Store_ZHN/MemberMall-gouwuche";
    }

    @RequestMapping("doDelxiangqing")
    public String doDelxiangqing(int commodityId,HttpSession session){
       Xiangqing xiangqing = (Xiangqing) session.getAttribute("xiangqing");
       xiangqing.del(commodityId);
        xiangqing.setPrices( xiangqing.getAllprices());
       session.setAttribute("xiangqing",xiangqing);
        return "Store_ZHN/MemberMall-gouwuche";
    }

    @RequestMapping("gouwuchejia")
    public String gouwuchejia (int commodityId,HttpSession session){
        Xiangqing xiangqing =new Xiangqing();
        xiangqing = (Xiangqing) session.getAttribute("xiangqing");
        AqbCommodity aqbCommodity = aqbCommodityService.getAqbCommodityBYAqbCommodity(commodityId);
        xiangqing.gouwuchejia(aqbCommodity);
        xiangqing.setPrices( xiangqing.getAllprices());
        session.setAttribute("xiangqing",xiangqing);
        return "Store_ZHN/MemberMall-gouwuche";
    }

    @RequestMapping("gouwuchejian")
    public String gouwuchejian(int commodityId,HttpSession session){
        Xiangqing xiangqing =new Xiangqing();
        xiangqing = (Xiangqing) session.getAttribute("xiangqing");
        AqbCommodity aqbCommodity = aqbCommodityService.getAqbCommodityBYAqbCommodity(commodityId);
        xiangqing.gouwuchejian(aqbCommodity);
        xiangqing.setPrices( xiangqing.getAllprices());
        session.setAttribute("xiangqing",xiangqing);
        return "Store_ZHN/MemberMall-gouwuche";
    }

    @RequestMapping(value = "jiesuan",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String jiesuan(HttpSession session,
                          @Param("prices")Float prices
    ){
        StringBuffer sb = new StringBuffer("{");
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        AqbUser aqbUser1 = aqbUserService.getByUserId(String.valueOf(aqbUser.getUserId()));
        double peoplemonney = aqbUser1.getMoney();
        System.out.println("peoplemonney="+peoplemonney);
        System.out.println("prices="+prices);
        if(peoplemonney>=prices){
            sb.append("\"flag\":\"T\"");
            Xiangqing xiangqing =new Xiangqing();
            AqbCommodity aqbCommodity =new AqbCommodity();
            xiangqing = (Xiangqing) session.getAttribute("xiangqing");
            List<AqbCommodity> aqbCommodityList = xiangqing.getAqbCommodity();
            for(int i=0;i<aqbCommodityList.size();i++){
                aqbCommodity=aqbCommodityList.get(i);
                if(aqbCommodity.getCommoditytype() == 1){  //为实物
                    AqbOrder aqbOrder =new AqbOrder();//储存主表
                    String dingdanNum = suiji.generateNumber2();
                    aqbOrder.setOrderNum(dingdanNum);
                    aqbOrder.setUserId( aqbUser.getUserId());
                    aqbOrder.setUserName(aqbUser.getUserName());
                    aqbOrder.setCommodityName(aqbCommodity.getCommodityName());
                    aqbOrder.setCommodityId(aqbCommodity.getCommodityId());
                    aqbOrder.setNumber(aqbCommodity.getNum());
                    aqbOrder.setPrice(aqbCommodity.getNewprice()*aqbCommodity.getNum());
                  boolean flag1 = aqbOrderService.addOrderById(aqbOrder); //储存主表

                    AqbEntityorder aqbEntityorder =new AqbEntityorder();  //储存分表
                    aqbEntityorder.setOrderName(dingdanNum);
                    aqbEntityorder.setDelivery(0);
                    aqbEntityorder.setFlow("未发货");
                    boolean flag2 = aqbEntityorderService.addEntiyorderByNum(aqbEntityorder);


                    int shuliang = aqbCommodityService.getShitiCount(aqbCommodity.getCommodityId()); //更新实体库存
                    aqbEntitycommodityService.updatecount( aqbCommodity.getCommodityId(),shuliang-aqbCommodity.getNum());

                }else {    //为红包
                    AqbOrder aqbOrder =new AqbOrder();//储存主表
                    String dingdanNum = suiji.generateNumber2();
                    aqbOrder.setOrderNum(dingdanNum);
                    aqbOrder.setUserId( aqbUser.getUserId());
                    aqbOrder.setUserName(aqbUser.getUserName());
                    aqbOrder.setCommodityName(aqbCommodity.getCommodityName());
                    aqbOrder.setCommodityId(aqbCommodity.getCommodityId());
                    aqbOrder.setNumber(aqbCommodity.getNum());
                    aqbOrder.setPrice(aqbCommodity.getNewprice()*aqbCommodity.getNum());
                    boolean flag1 = aqbOrderService.addOrderById(aqbOrder); //储存主表


                    AqbPacket aqbPacket = new AqbPacket();     //改动用户表
                    aqbPacket.setUserId(aqbUser.getUserId());
                    int flag = aqbCommodity.getCommodityId();
                    if(flag == 9){
                        aqbPacket.setType("hongbao01");
                    }else if(flag == 10){
                        aqbPacket.setType("hongbao04");
                    }else if(flag == 11){
                        aqbPacket.setType("hongbao05");
                    }else if(flag == 12){
                        aqbPacket.setType("hongbao06");
                    }
                    aqbPacket.setUseCondition(1000);
                    aqbPacketService.addhongbao(aqbPacket);   //改动用户表

                }

            }
            int newprices =(int)(peoplemonney - prices);   //更新用户钱帮币
            aqbUserService.modifyMoney(newprices,aqbUser1.getUserId());
            aqbUser.setMoney(newprices);
            session.setAttribute(Constants.USER_SESSION,aqbUser);
            session.removeAttribute("xiangqing");
        }else {
            sb.append("\"flag\":\"F\"");
        }
        sb.append("}");
        return sb.toString();
    }

    @RequestMapping("fahuo")
    public String fahuo(String orderNum,HttpSession session){
        aqbEntityorderService.updataEntiyorder(orderNum);
        return "Store_ZHN/MemberMall-fahuo";
    }
}
